package redis.inaction.ratelimiter.support;

import org.springframework.cloud.gateway.route.Route;
import org.springframework.web.server.ServerWebExchange;

import java.util.Map;

import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR;
import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.getUriTemplateVariables;

public class RouteApiUtils {

    public static String getApiCode(ServerWebExchange exchange, String apiCodeName){
        return getUriTemplateVariables(exchange).get(apiCodeName);
    }

    public static Map<String, Object> getRouteApi(ServerWebExchange exchange, String apiCodeName){
        String apiCode = getApiCode(exchange, apiCodeName);
        if(apiCode == null){
            return null;
        }
        Map<String, Object> routeApisMap = (Map<String, Object>) getRouteMetadataMap(exchange).get("apiMap");
        return routeApisMap == null ? null : (Map<String, Object>)routeApisMap.get(apiCode);
    }

    public static Map<String, Object> getRouteMetadataMap(ServerWebExchange exchange){
        Map<String, Object> meta = exchange.getAttribute("route_meta_map");
        if(meta == null){
            Route route = exchange.getAttribute(GATEWAY_ROUTE_ATTR);
            meta = route.getMetadata();
            exchange.getAttributes().put("route_meta_map", meta);
        }
        return meta;
    }
}
